<template>
  <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑客户' : '添加客户'" width="80%">
    <el-form :model="customerForm" :rules="rules" ref="customerFormRef" label-width="120px">
      <!-- 左侧标签栏 -->
      <div class="form-labels">
        <div class="label-item" :class="{ 'active': currentStep === 1 }" @click="currentStep = 1">
          基本信息
        </div>
        <div class="label-item" :class="{ 'active': currentStep === 2 }" @click="currentStep = 2">
          财务信息
        </div>
      </div>

      <!-- 右侧输入框 -->
      <div class="form-inputs">
        <!-- 基本信息 -->
        <div class="form-section" v-if="currentStep === 1">
          <el-form 
          :model="customerForm" 
          :rules="rules" 
          ref="customerFormRef" 
          label-width="120px" 
          label-position="left"
          >
            <el-form-item label="统一社会信用代码" prop="creditCode">
              <el-input v-model="customerForm.creditCode" placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="公司名称" prop="companyName">
              <el-input v-model="customerForm.companyName" placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="注册资本(万元)">
              <el-input v-model="customerForm.registerCapital" placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="注册地址" prop="registerAddress">
              <el-cascader v-model="customerForm.registerAddress" :options="addressOptions" placeholder="请选择省市区"
                style="width: 100%"></el-cascader>
              <el-input v-model="customerForm.registerDetailAddress" placeholder="请输入详细地址"></el-input>
            </el-form-item>
            <el-form-item label="主营业务" prop="mainBusiness">
              <el-input type="textarea" v-model="customerForm.mainBusiness" placeholder="请输入描述，少于128个字，非必填"></el-input>
            </el-form-item>
            <el-form-item label="默认交货地址" prop="deliveryAddress">
              <el-cascader v-model="customerForm.deliveryAddress" :options="addressOptions" placeholder="请选择省市区"
                style="width: 100%"></el-cascader>
              <el-input v-model="customerForm.deliveryDetailAddress" placeholder="请输入详细地址"></el-input>
            </el-form-item>
            <el-form-item label="联系人" prop="contactPerson">
              <el-input v-model="customerForm.contactPerson" placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="联系方式" prop="contactInfo">
              <el-input v-model="customerForm.contactInfo" placeholder="请输入"></el-input>
            </el-form-item>
          </el-form>
        </div>

        <!-- 财务信息 -->
        <div class="form-section" v-if="currentStep === 2">
          <el-form-item label="纳税人类型" prop="taxpayerType">
            <el-select v-model="customerForm.taxpayerType" placeholder="请选择">
              <el-option label="一般纳税人" value="general"></el-option>
              <el-option label="小规模纳税人" value="small"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发票类型" prop="invoiceType">
            <el-select v-model="customerForm.invoiceType" placeholder="请选择">
              <el-option label="增值税专用发票" value="special"></el-option>
              <el-option label="增值税普通发票" value="common"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="开票户行" prop="bankName">
            <el-input v-model="customerForm.bankName" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="开票户行帐号" prop="bankAccount">
            <el-input v-model="customerForm.bankAccount" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="开票地址" prop="billingAddress">
            <el-cascader v-model="customerForm.billingAddress" :options="addressOptions" placeholder="请选择省市区"
              style="width: 100%"></el-cascader>
            <el-input v-model="customerForm.billingDetailAddress" placeholder="请输入详细地址"></el-input>
          </el-form-item>
        </div>
      </div>

      <div class="form-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button v-if="currentStep > 1" @click="handlePrev">上一步</el-button>
        <el-button v-if="currentStep < 2" type="primary" @click="handleNext">下一步</el-button>
        <el-button v-if="currentStep === 2" type="primary" @click="handleSubmit">{{ isEdit ? '更新' : '确定' }}</el-button>
      </div>
    </el-form>
  </el-dialog>
</template>

<script setup>
import { ref, reactive } from "vue";
import { ElMessage } from "element-plus";

const dialogVisible = ref(false);
const customerFormRef = ref(null);
const currentStep = ref(1); // 当前步骤
const isEdit = ref(false); // 是否为编辑模式
const editCustomerId = ref(null); // 编辑的客户ID

// 定义 emit 用于向父组件传递数据
const emit = defineEmits(["customerAdded", "customerUpdated"]);

const customerForm = reactive({
  id: 0,
  creditCode: "",
  companyName: "",
  registerCapital: "",
  registerAddress: [],
  registerDetailAddress: "",
  mainBusiness: "",
  deliveryAddress: [],
  deliveryDetailAddress: "",
  contactPerson: "",
  contactInfo: "",
  taxpayerType: "",
  invoiceType: "",
  bankName: "",
  bankAccount: "",
  billingAddress: [],
  billingDetailAddress: "",
  contractAmount: "0万元",
  lastInteractionTime: ""
});

const rules = {
  creditCode: [
    { required: true, message: "请输入统一社会信用代码", trigger: "blur" }
  ],
  companyName: [{ required: true, message: "请输入公司名称", trigger: "blur" }],
  registerAddress: [
    { required: true, message: "请选择注册地址", trigger: "change" }
  ],
  registerDetailAddress: [
    { required: true, message: "请输入详细地址", trigger: "blur" }
  ],
  deliveryAddress: [
    { required: true, message: "请选择默认交货地址", trigger: "change" }
  ],
  deliveryDetailAddress: [
    { required: true, message: "请输入详细地址", trigger: "blur" }
  ],
  contactPerson: [{ required: true, message: "请输入联系人", trigger: "blur" }],
  contactInfo: [{ required: true, message: "请输入联系方式", trigger: "blur" }],
  taxpayerType: [
    { required: true, message: "请选择纳税人类型", trigger: "change" }
  ],
  invoiceType: [
    { required: true, message: "请选择发票类型", trigger: "change" }
  ],
  bankName: [{ required: true, message: "请输入开票户行", trigger: "blur" }],
  bankAccount: [
    { required: true, message: "请输入开票户行帐号", trigger: "blur" }
  ],
  billingAddress: [
    { required: true, message: "请选择开票地址", trigger: "change" }
  ],
  billingDetailAddress: [
    { required: true, message: "请输入开票详细地址", trigger: "blur" }
  ]
};

const addressOptions = [
  {
    value: "湖北省",
    label: "湖北省",
    children: [
      {
        value: "武汉市",
        label: "武汉市",
        children: [
          { value: "汉阳区", label: "汉阳区" },
          { value: "武昌区", label: "武昌区" }
        ]
      }
    ]
  }
];

// 打开添加客户对话框
const openDialog = () => {
  isEdit.value = false;
  dialogVisible.value = true;
  currentStep.value = 1;
  editCustomerId.value = null;
  // 重置表单数据
  resetForm();
};

// 打开编辑客户对话框
const openEditDialog = customerData => {
  isEdit.value = true;
  dialogVisible.value = true;
  currentStep.value = 1;
  editCustomerId.value = customerData.id;

  // 填充表单数据
  Object.keys(customerForm).forEach(key => {
    if (customerData[key] !== undefined) {
      customerForm[key] = customerData[key];
    }
  });
};

const resetForm = () => {
  Object.keys(customerForm).forEach(key => {
    if (Array.isArray(customerForm[key])) {
      customerForm[key] = [];
    } else if (typeof customerForm[key] === "string") {
      customerForm[key] = "";
    } else if (typeof customerForm[key] === "number") {
      customerForm[key] = 0;
    }
  });
};

const handleNext = () => {
  customerFormRef.value.validate(valid => {
    if (valid) {
      currentStep.value++;
    } else {
      ElMessage.error("请检查表单填写是否正确");
      return false;
    }
  });
};

const handlePrev = () => {
  currentStep.value--;
};

const handleSubmit = () => {
  customerFormRef.value.validate(valid => {
    if (valid) {
      if (!isEdit.value) {
        // 添加新客户
        customerForm.id = Date.now();
        customerForm.lastInteractionTime = new Date()
          .toLocaleString("zh-CN", {
            year: "numeric",
            month: "2-digit",
            day: "2-digit",
            hour: "2-digit",
            minute: "2-digit",
            second: "2-digit"
          })
          .replace(/\//g, "-");

        ElMessage.success("添加成功");
        emit("customerAdded", { ...customerForm });
      } else {
        // 更新客户信息
        customerForm.lastInteractionTime = new Date()
          .toLocaleString("zh-CN", {
            year: "numeric",
            month: "2-digit",
            day: "2-digit",
            hour: "2-digit",
            minute: "2-digit",
            second: "2-digit"
          })
          .replace(/\//g, "-");

        ElMessage.success("更新成功");
        emit("customerUpdated", { ...customerForm });
      }

      dialogVisible.value = false;
    } else {
      ElMessage.error("请检查表单填写是否正确");
      return false;
    }
  });
};

const handleCancel = () => {
  dialogVisible.value = false;
};

defineExpose({ openDialog, openEditDialog });
</script>

<style scoped>
.form-section {
  margin-bottom: 20px;
}

.form-section h3 {
  margin-bottom: 10px;
  background-color: #409eff;
  color: white;
  padding: 5px 10px;
}

.form-labels {
  display: flex;
  flex-direction: column;
  width: 20%;
  background-color: #f5f7fa;
  padding: 10px;
  float: left;
  min-height: 400px;
}

.label-item {
  margin-bottom: 10px;
  font-weight: bold;
  padding: 10px;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.3s;
  font-size: 14px;
  /* 设置字体大小 */
  text-align: left;
  /* 左对齐 */
  white-space: nowrap;
  /* 防止换行 */
  overflow: hidden;
  /* 隐藏溢出内容 */
  text-overflow: ellipsis;
  /* 文本溢出显示省略号 */
}

.label-item:hover {
  background-color: #e4e7ed;
}

.label-item.active {
  background-color: #409eff;
  color: white;
}

.form-inputs {
  display: flex;
  flex-direction: column;
  width: 80%;
  padding: 10px;
  float: right;
}

:deep(.el-form-item__label) {
  text-align: left !important;
  vertical-align: middle;
  float: left;
  font-size: 12px;
  color: #606266;
  line-height: 40px;
  padding: 0 12px 0 0;
  box-sizing: border-box;
  white-space: nowrap;
}

:deep(.el-form-item) {
  margin-bottom: 10px;
}

:deep(.el-form-item__content) {
  line-height: 40px;
  position: relative;
  font-size: 14px;
}

.form-footer {
  text-align: right;
  margin-top: 20px;
  clear: both;
}
</style>